home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / rdflib / Graph.py < prev    next >
Encoding:
Python Source  |  2009-03-04  |  44.5 KB  |  1,259 lines

  1. from __future__ import generators
  2.  
  3. __doc__="""
  4. Instanciating Graphs with default store (IOMemory) and default identifier (a BNode):
  5.  
  6.     >>> g=Graph()
  7.     >>> g.store.__class__
  8.     <class 'rdflib.store.IOMemory.IOMemory'>
  9.     >>> g.identifier.__class__
  10.     <class 'rdflib.BNode.BNode'>
  11.  
  12. Instanciating Graphs with a specific kind of store (IOMemory) and a default identifier (a BNode):
  13.  
  14. Other store kinds: Sleepycat, MySQL, ZODB, SQLite
  15.  
  16.     >>> store = plugin.get('IOMemory',Store)()
  17.     >>> store.__class__.__name__
  18.     'IOMemory'
  19.     >>> graph = Graph(store)
  20.     >>> graph.store.__class__
  21.     <class 'rdflib.store.IOMemory.IOMemory'>
  22.  
  23. Instanciating Graphs with Sleepycat store and an identifier - <http://rdflib.net>:
  24.  
  25.     >>> g=Graph('Sleepycat',URIRef("http://rdflib.net"))
  26.     >>> g.identifier
  27.     rdflib.URIRef('http://rdflib.net')
  28.     >>> str(g)
  29.     "<http://rdflib.net> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Sleepycat']."
  30.  
  31. Creating a ConjunctiveGraph - The top level container for all named Graphs in a 'database':
  32.  
  33.     >>> g=ConjunctiveGraph()
  34.     >>> str(g.default_context)
  35.     "[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]."
  36.  
  37. Adding / removing reified triples to Graph and iterating over it directly or via triple pattern:
  38.     
  39.     >>> g=Graph('IOMemory')
  40.     >>> statementId = BNode()
  41.     >>> print len(g)
  42.     0
  43.     >>> g.add((statementId,RDF.type,RDF.Statement))
  44.     >>> g.add((statementId,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  45.     >>> g.add((statementId,RDF.predicate,RDFS.label))
  46.     >>> g.add((statementId,RDF.object,Literal("Conjunctive Graph")))
  47.     >>> print len(g)
  48.     4
  49.     >>> for s,p,o in g:  print type(s)
  50.     ...
  51.     <class 'rdflib.BNode.BNode'>
  52.     <class 'rdflib.BNode.BNode'>
  53.     <class 'rdflib.BNode.BNode'>
  54.     <class 'rdflib.BNode.BNode'>
  55.     
  56.     >>> for s,p,o in g.triples((None,RDF.object,None)):  print o
  57.     ...
  58.     Conjunctive Graph
  59.     >>> g.remove((statementId,RDF.type,RDF.Statement))
  60.     >>> print len(g)
  61.     3
  62.  
  63. None terms in calls to triple can be thought of as 'open variables'  
  64.  
  65. Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:
  66.     
  67.     >>> store = plugin.get('IOMemory',Store)()
  68.     >>> g1 = Graph(store)
  69.     >>> g2 = Graph(store)
  70.     >>> g3 = Graph(store)
  71.     >>> stmt1 = BNode()
  72.     >>> stmt2 = BNode()
  73.     >>> stmt3 = BNode()
  74.     >>> g1.add((stmt1,RDF.type,RDF.Statement))
  75.     >>> g1.add((stmt1,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  76.     >>> g1.add((stmt1,RDF.predicate,RDFS.label))
  77.     >>> g1.add((stmt1,RDF.object,Literal("Conjunctive Graph")))
  78.     >>> g2.add((stmt2,RDF.type,RDF.Statement))
  79.     >>> g2.add((stmt2,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  80.     >>> g2.add((stmt2,RDF.predicate,RDF.type))
  81.     >>> g2.add((stmt2,RDF.object,RDFS.Class))
  82.     >>> g3.add((stmt3,RDF.type,RDF.Statement))
  83.     >>> g3.add((stmt3,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  84.     >>> g3.add((stmt3,RDF.predicate,RDFS.comment))
  85.     >>> g3.add((stmt3,RDF.object,Literal("The top-level aggregate graph - The sum of all named graphs within a Store")))
  86.     >>> len(list(ConjunctiveGraph(store).subjects(RDF.type,RDF.Statement)))
  87.     3
  88.     >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(RDF.type,RDF.Statement)))
  89.     2
  90.  
  91. ConjunctiveGraphs have a 'quads' method which returns quads instead of triples, where the fourth item
  92. is the Graph (or subclass thereof) instance in which the triple was asserted:
  93.     
  94.     >>> from sets import Set    
  95.     >>> uniqueGraphNames = Set([graph.identifier for s,p,o,graph in ConjunctiveGraph(store).quads((None,RDF.predicate,None))])
  96.     >>> len(uniqueGraphNames)
  97.     3
  98.     >>> unionGraph = ReadOnlyGraphAggregate([g1,g2])
  99.     >>> uniqueGraphNames = Set([graph.identifier for s,p,o,graph in unionGraph.quads((None,RDF.predicate,None))])
  100.     >>> len(uniqueGraphNames)
  101.     2
  102.      
  103. Parsing N3 from StringIO
  104.  
  105.     >>> g2=Graph()
  106.     >>> src = \"\"\"
  107.     ... @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
  108.     ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  109.     ... [ a rdf:Statement ;
  110.     ...   rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
  111.     ...   rdf:predicate rdfs:label;
  112.     ...   rdf:object "Conjunctive Graph" ] \"\"\"
  113.     >>> g2=g2.parse(StringIO(src),format='n3')
  114.     >>> print len(g2)
  115.     4
  116.  
  117. Using Namespace class:
  118.  
  119.     >>> RDFLib = Namespace('http://rdflib.net')
  120.     >>> RDFLib.ConjunctiveGraph
  121.     rdflib.URIRef('http://rdflib.netConjunctiveGraph')
  122.     >>> RDFLib['Graph']
  123.     rdflib.URIRef('http://rdflib.netGraph')
  124.  
  125. SPARQL Queries
  126.  
  127.     >>> print len(g)
  128.     3
  129.     >>> q = \'\'\'
  130.     ... PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?pred WHERE { ?stmt rdf:predicate ?pred. }
  131.     ... \'\'\'   
  132.     >>> for pred in g.query(q):  print pred
  133.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  134.  
  135. SPARQL Queries with namespace bindings as argument
  136.  
  137.     >>> nsMap = {u"rdf":RDF.RDFNS}
  138.     >>> for pred in g.query("SELECT ?pred WHERE { ?stmt rdf:predicate ?pred. }", initNs=nsMap): print pred
  139.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  140.  
  141. Parameterized SPARQL Queries
  142.  
  143.     >>> top = { Variable("?term") : RDF.predicate }
  144.     >>> for pred in g.query("SELECT ?pred WHERE { ?stmt ?term ?pred. }", initBindings=top): print pred
  145.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  146.  
  147. """
  148.  
  149.  
  150. from cStringIO import StringIO
  151. from rdflib import URIRef, BNode, Namespace, Literal, Variable
  152. from rdflib import RDF, RDFS
  153.  
  154. from rdflib.Node import Node
  155.  
  156. from rdflib import plugin, exceptions
  157.  
  158. from rdflib.store import Store
  159.  
  160. from rdflib.syntax.serializer import Serializer
  161. from rdflib.syntax.parsers import Parser
  162. from rdflib.syntax.NamespaceManager import NamespaceManager
  163. from rdflib import sparql
  164. from rdflib.QueryResult import QueryResult
  165. from rdflib.URLInputSource import URLInputSource
  166. from xml.sax.xmlreader import InputSource
  167. from xml.sax.saxutils import prepare_input_source
  168.  
  169. import logging
  170. _logger = logging.getLogger("rdflib.Graph")
  171.  
  172. #import md5
  173. import random
  174. import warnings
  175.  
  176. try:
  177.     from hashlib import md5
  178. except ImportError:
  179.     from md5 import md5    
  180.  
  181. def describe(terms,bindings,graph):
  182.     """ 
  183.     Default DESCRIBE returns all incomming and outgoing statements about the given terms 
  184.     """
  185.     from rdflib.sparql.sparqlOperators import getValue
  186.     g=Graph()
  187.     terms=[getValue(i)(bindings) for i in terms]
  188.     for s,p,o in graph.triples_choices((terms,None,None)):
  189.         g.add((s,p,o))
  190.     for s,p,o in graph.triples_choices((None,None,terms)):
  191.         g.add((s,p,o))
  192.     return g
  193.  
  194. class Graph(Node):
  195.     """An RDF Graph
  196.  
  197.     The constructor accepts one argument, the 'store'
  198.     that will be used to store the graph data (see the 'store'
  199.     package for stores currently shipped with rdflib).
  200.  
  201.     Stores can be context-aware or unaware.  Unaware stores take up
  202.     (some) less space but cannot support features that require
  203.     context, such as true merging/demerging of sub-graphs and
  204.     provenance.
  205.  
  206.     The Graph constructor can take an identifier which identifies the Graph
  207.     by name.  If none is given, the graph is assigned a BNode for it's identifier.
  208.     For more on named graphs, see: http://www.w3.org/2004/03/trix/
  209.  
  210.     Ontology for __str__ provenance terms:
  211.  
  212.     @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
  213.     @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  214.     @prefix : <http://rdflib.net/store#> .
  215.     @prefix rdfg: <http://www.w3.org/2004/03/trix/rdfg-1/>.
  216.     @prefix owl: <http://www.w3.org/2002/07/owl#>.
  217.     @prefix log: <http://www.w3.org/2000/10/swap/log#>.
  218.     @prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
  219.  
  220.     :Store a owl:Class;
  221.         rdfs:subClassOf <http://xmlns.com/wordnet/1.6/Electronic_database>;
  222.         rdfs:subClassOf
  223.             [a owl:Restriction;
  224.              owl:onProperty rdfs:label;
  225.              owl:allValuesFrom [a owl:DataRange;
  226.                                 owl:oneOf ("IOMemory"
  227.                                            "Sleepcat"
  228.                                            "MySQL"
  229.                                            "Redland"
  230.                                            "REGEXMatching"
  231.                                            "ZODB"
  232.                                            "AuditableStorage"
  233.                                            "Memory")]
  234.             ].
  235.  
  236.     :ConjunctiveGraph a owl:Class;
  237.         rdfs:subClassOf rdfg:Graph;
  238.         rdfs:label "The top-level graph within the store - the union of all the Graphs within."
  239.         rdfs:seeAlso <http://rdflib.net/rdf_store/#ConjunctiveGraph>.
  240.  
  241.     :DefaultGraph a owl:Class;
  242.         rdfs:subClassOf rdfg:Graph;
  243.         rdfs:label "The 'default' subgraph of a conjunctive graph".
  244.  
  245.  
  246.     :identifier a owl:Datatypeproperty;
  247.         rdfs:label "The store-associated identifier of the formula. ".
  248.         rdfs:domain log:Formula
  249.         rdfs:range xsd:anyURI;
  250.  
  251.     :storage a owl:ObjectProperty;
  252.         rdfs:domain [
  253.             a owl:Class;
  254.             owl:unionOf (log:Formula rdfg:Graph :ConjunctiveGraph)
  255.         ];
  256.         rdfs:range :Store.
  257.  
  258.     :default_context a owl:FunctionalProperty;
  259.         rdfs:label "The default context for a conjunctive graph";
  260.         rdfs:domain :ConjunctiveGraph;
  261.         rdfs:range :DefaultGraph.
  262.  
  263.  
  264.     {?cg a :ConjunctiveGraph;:storage ?store}
  265.       => {?cg owl:sameAs ?store}.
  266.  
  267.     {?subGraph rdfg:subGraphOf ?cg;a :DefaultGraph}
  268.       => {?cg a :ConjunctiveGraph;:default_context ?subGraphOf} .
  269.     """
  270.  
  271.     def __init__(self, store='default', identifier=None,
  272.                  namespace_manager=None):
  273.         super(Graph, self).__init__()
  274.         self.__identifier = identifier or BNode()
  275.         if not isinstance(store, Store):
  276.             # TODO: error handling
  277.             self.__store = store = plugin.get(store, Store)()
  278.         else:
  279.             self.__store = store
  280.         self.__namespace_manager = namespace_manager
  281.         self.context_aware = False
  282.         self.formula_aware = False
  283.  
  284.     def __get_store(self):
  285.         return self.__store
  286.     store = property(__get_store)
  287.  
  288.     def __get_identifier(self):
  289.         return self.__identifier
  290.     identifier = property(__get_identifier)
  291.  
  292.     def _get_namespace_manager(self):
  293.         if self.__namespace_manager is None:
  294.             self.__namespace_manager = NamespaceManager(self)
  295.         return self.__namespace_manager
  296.  
  297.     def _set_namespace_manager(self, nm):
  298.         self.__namespace_manager = nm
  299.     namespace_manager = property(_get_namespace_manager, _set_namespace_manager)
  300.  
  301.     def __repr__(self):
  302.         return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
  303.  
  304.     def __str__(self):
  305.         if isinstance(self.identifier,URIRef):
  306.             return "%s a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']."%(self.identifier.n3(),self.store.__class__.__name__)
  307.         else:
  308.             return "[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']]."%(self.store.__class__.__name__)
  309.  
  310.     def destroy(self, configuration):
  311.         """Destroy the store identified by `configuration` if supported"""
  312.         self.__store.destroy(configuration)
  313.  
  314.     #Transactional interfaces (optional)
  315.     def commit(self):
  316.         """Commits active transactions"""
  317.         self.__store.commit()
  318.  
  319.     def rollback(self):
  320.         """Rollback active transactions"""
  321.         self.__store.rollback()
  322.  
  323.     def open(self, configuration, create=False):
  324.         """Open the graph store
  325.  
  326.         Might be necessary for stores that require opening a connection to a
  327.         database or acquiring some resource.
  328.         """
  329.         return self.__store.open(configuration, create)
  330.  
  331.     def close(self, commit_pending_transaction=False):
  332.         """Close the graph store
  333.  
  334.         Might be necessary for stores that require closing a connection to a
  335.         database or releasing some resource.
  336.         """
  337.         self.__store.close(commit_pending_transaction=commit_pending_transaction)
  338.  
  339.     def add(self, (s, p, o)):
  340.         """Add a triple with self as context"""
  341.         self.__store.add((s, p, o), self, quoted=False)
  342.  
  343.     def addN(self, quads):
  344.         """Add a sequence of triple with context"""
  345.         self.__store.addN([(s, p, o, c) for s, p, o, c in quads
  346.                                         if isinstance(c, Graph)
  347.                                         and c.identifier is self.identifier])
  348.  
  349.     def remove(self, (s, p, o)):
  350.         """Remove a triple from the graph
  351.  
  352.         If the triple does not provide a context attribute, removes the triple
  353.         from all contexts.
  354.         """
  355.         self.__store.remove((s, p, o), context=self)
  356.  
  357.     def triples(self, (s, p, o)):
  358.         """Generator over the triple store
  359.  
  360.         Returns triples that match the given triple pattern. If triple pattern
  361.         does not provide a context, all contexts will be searched.
  362.         """
  363.         for (s, p, o), cg in self.__store.triples((s, p, o), context=self):
  364.             yield (s, p, o)
  365.  
  366.     def __len__(self):
  367.         """Returns the number of triples in the graph
  368.  
  369.         If context is specified then the number of triples in the context is
  370.         returned instead.
  371.         """
  372.         return self.__store.__len__(context=self)
  373.  
  374.     def __iter__(self):
  375.         """Iterates over all triples in the store"""
  376.         return self.triples((None, None, None))
  377.  
  378.     def __contains__(self, triple):
  379.         """Support for 'triple in graph' syntax"""
  380.         for triple in self.triples(triple):
  381.             return 1
  382.         return 0
  383.  
  384.     def __hash__(self):
  385.         return hash(self.identifier)
  386.  
  387.     def md5_term_hash(self):
  388.         d = md5(str(self.identifier))
  389.         d.update("G")
  390.         return d.hexdigest()
  391.  
  392.     def __cmp__(self, other):
  393.         if other is None:
  394.             return -1
  395.         elif isinstance(other, Graph):
  396.             return cmp(self.identifier, other.identifier)
  397.         else:
  398.             #Note if None is considered equivalent to owl:Nothing
  399.             #Then perhaps a graph with length 0 should be considered
  400.             #equivalent to None (if compared to it)?
  401.             return 1
  402.  
  403.     def __iadd__(self, other):
  404.         """Add all triples in Graph other to Graph"""
  405.         for triple in other:
  406.             self.add(triple)
  407.         return self
  408.  
  409.     def __isub__(self, other):
  410.         """Subtract all triples in Graph other from Graph"""
  411.         for triple in other:
  412.             self.remove(triple)
  413.         return self
  414.  
  415.     def __add__(self,other) :
  416.         """Set theoretical union"""
  417.         retval = Graph()
  418.         for x in self.graph:
  419.             retval.add(x)
  420.         for y in other.graph:
  421.             retval.add(y)
  422.         return retval
  423.  
  424.     def __mul__(self,other) :
  425.         """Set theoretical intersection"""
  426.         retval = Graph()
  427.         for x in other.graph:
  428.             if x in self.graph: 
  429.                 retval.add(x)
  430.         return retval
  431.  
  432.     def __sub__(self,other) :
  433.         """Set theoretical difference"""
  434.         retval = Graph()
  435.         for x in self.graph:
  436.             if not x in other.graph : 
  437.                 retval.add(x)
  438.         return retval
  439.  
  440.     # Conv. methods
  441.  
  442.     def set(self, (subject, predicate, object)):
  443.         """Convenience method to update the value of object
  444.  
  445.         Remove any existing triples for subject and predicate before adding
  446.         (subject, predicate, object).
  447.         """
  448.         self.remove((subject, predicate, None))
  449.         self.add((subject, predicate, object))
  450.  
  451.     def subjects(self, predicate=None, object=None):
  452.         """A generator of subjects with the given predicate and object"""
  453.         for s, p, o in self.triples((None, predicate, object)):
  454.             yield s
  455.  
  456.     def predicates(self, subject=None, object=None):
  457.         """A generator of predicates with the given subject and object"""
  458.         for s, p, o in self.triples((subject, None, object)):
  459.             yield p
  460.  
  461.     def objects(self, subject=None, predicate=None):
  462.         """A generator of objects with the given subject and predicate"""
  463.         for s, p, o in self.triples((subject, predicate, None)):
  464.             yield o
  465.  
  466.     def subject_predicates(self, object=None):
  467.         """A generator of (subject, predicate) tuples for the given object"""
  468.         for s, p, o in self.triples((None, None, object)):
  469.             yield s, p
  470.  
  471.     def subject_objects(self, predicate=None):
  472.         """A generator of (subject, object) tuples for the given predicate"""
  473.         for s, p, o in self.triples((None, predicate, None)):
  474.             yield s, o
  475.  
  476.     def predicate_objects(self, subject=None):
  477.         """A generator of (predicate, object) tuples for the given subject"""
  478.         for s, p, o in self.triples((subject, None, None)):
  479.             yield p, o
  480.  
  481.     def triples_choices(self, (subject, predicate, object_),context=None):
  482.         for (s, p, o), cg in self.store.triples_choices(
  483.             (subject, predicate, object_), context=self):
  484.             yield (s, p, o)
  485.  
  486.     def value(self, subject=None, predicate=RDF.value, object=None,
  487.               default=None, any=True):
  488.         """Get a value for a pair of two criteria
  489.  
  490.         Exactly one of subject, predicate, object must be None. Useful if one
  491.         knows that there may only be one value.
  492.  
  493.         It is one of those situations that occur a lot, hence this
  494.         'macro' like utility
  495.  
  496.         Parameters:
  497.         -----------
  498.         subject, predicate, object  -- exactly one must be None
  499.         default -- value to be returned if no values found
  500.         any -- if True:
  501.                  return any value in the case there is more than one
  502.                else:
  503.                  raise UniquenessError
  504.         """
  505.         retval = default
  506.  
  507.         if (subject is None and predicate is None) or \
  508.                 (subject is None and object is None) or \
  509.                 (predicate is None and object is None):
  510.             return None
  511.         
  512.         if object is None:
  513.             values = self.objects(subject, predicate)
  514.         if subject is None:
  515.             values = self.subjects(predicate, object)
  516.         if predicate is None:
  517.             values = self.predicates(subject, object)
  518.  
  519.         try:
  520.             retval = values.next()
  521.         except StopIteration, e:
  522.             retval = default
  523.         else:
  524.             if any is False:
  525.                 try:
  526.                     next = values.next()
  527.                     msg = ("While trying to find a value for (%s, %s, %s) the "
  528.                            "following multiple values where found:\n" %
  529.                            (subject, predicate, object))
  530.                     triples = self.store.triples((subject, predicate, object), None)
  531.                     for (s, p, o), contexts in triples:
  532.                         msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
  533.                             s, p, o, list(contexts))
  534.                     raise exceptions.UniquenessError(msg)
  535.                 except StopIteration, e:
  536.                     pass
  537.         return retval
  538.  
  539.     def label(self, subject, default=''):
  540.         """Query for the RDFS.label of the subject
  541.  
  542.         Return default if no label exists
  543.         """
  544.         if subject is None:
  545.             return default
  546.         return self.value(subject, RDFS.label, default=default, any=True)
  547.  
  548.     def comment(self, subject, default=''):
  549.         """Query for the RDFS.comment of the subject
  550.  
  551.         Return default if no comment exists
  552.         """
  553.         if subject is None:
  554.             return default
  555.         return self.value(subject, RDFS.comment, default=default, any=True)
  556.  
  557.     def items(self, list):
  558.         """Generator over all items in the resource specified by list
  559.  
  560.         list is an RDF collection.
  561.         """
  562.         while list:
  563.             item = self.value(list, RDF.first)
  564.             if item:
  565.                 yield item
  566.             list = self.value(list, RDF.rest)
  567.  
  568.     def transitiveClosure(self,func,arg):
  569.         """
  570.         Generates transitive closure of a user-defined 
  571.         function against the graph
  572.         
  573.         >>> from rdflib.Collection import Collection
  574.         >>> g=Graph()
  575.         >>> a=BNode('foo')
  576.         >>> b=BNode('bar')
  577.         >>> c=BNode('baz')
  578.         >>> g.add((a,RDF.first,RDF.type))
  579.         >>> g.add((a,RDF.rest,b))
  580.         >>> g.add((b,RDF.first,RDFS.label))
  581.         >>> g.add((b,RDF.rest,c))
  582.         >>> g.add((c,RDF.first,RDFS.comment))
  583.         >>> g.add((c,RDF.rest,RDF.nil))
  584.         >>> def topList(node,g):
  585.         ...    for s in g.subjects(RDF.rest,node):
  586.         ...       yield s
  587.         >>> def reverseList(node,g):
  588.         ...    for f in g.objects(node,RDF.first):
  589.         ...       print f
  590.         ...    for s in g.subjects(RDF.rest,node):
  591.         ...       yield s
  592.         
  593.         >>> [rt for rt in g.transitiveClosure(topList,RDF.nil)]
  594.         [rdflib.BNode('baz'), rdflib.BNode('bar'), rdflib.BNode('foo')]
  595.         
  596.         >>> [rt for rt in g.transitiveClosure(reverseList,RDF.nil)]
  597.         http://www.w3.org/2000/01/rdf-schema#comment
  598.         http://www.w3.org/2000/01/rdf-schema#label
  599.         http://www.w3.org/1999/02/22-rdf-syntax-ns#type
  600.         [rdflib.BNode('baz'), rdflib.BNode('bar'), rdflib.BNode('foo')]
  601.         
  602.         """
  603.         for rt in func(arg,self):
  604.             yield rt
  605.             for rt_2 in self.transitiveClosure(func,rt):
  606.                 yield rt_2
  607.  
  608.     def transitive_objects(self, subject, property, remember=None):
  609.         """Transitively generate objects for the `property` relationship
  610.  
  611.         Generated objects belong to the depth first transitive closure of the
  612.         `property` relationship starting at `subject`.
  613.         """
  614.         if remember is None:
  615.             remember = {}
  616.         if subject in remember:
  617.             return
  618.         remember[subject] = 1
  619.         yield subject
  620.         for object in self.objects(subject, property):
  621.             for o in self.transitive_objects(object, property, remember):
  622.                 yield o
  623.  
  624.     def transitive_subjects(self, predicate, object, remember=None):
  625.         """Transitively generate objects for the `property` relationship
  626.  
  627.         Generated objects belong to the depth first transitive closure of the
  628.         `property` relationship starting at `subject`.
  629.         """
  630.         if remember is None:
  631.             remember = {}
  632.         if object in remember:
  633.             return
  634.         remember[object] = 1
  635.         yield object
  636.         for subject in self.subjects(predicate, object):
  637.             for s in self.transitive_subjects(predicate, subject, remember):
  638.                 yield s
  639.  
  640.     def seq(self, subject):
  641.         """Check if subject is an rdf:Seq
  642.  
  643.         If yes, it returns a Seq class instance, None otherwise.
  644.         """
  645.         if (subject, RDF.type, RDF.Seq) in self:
  646.             return Seq(self, subject)
  647.         else:
  648.             return None
  649.  
  650.     def qname(self, uri):
  651.         return self.namespace_manager.qname(uri)
  652.  
  653.     def compute_qname(self, uri):
  654.         return self.namespace_manager.compute_qname(uri)
  655.  
  656.     def bind(self, prefix, namespace, override=True):
  657.         """Bind prefix to namespace
  658.  
  659.         If override is True will bind namespace to given prefix if namespace
  660.         was already bound to a different prefix.
  661.         """
  662.         return self.namespace_manager.bind(prefix, namespace, override=override)
  663.  
  664.     def namespaces(self):
  665.         """Generator over all the prefix, namespace tuples"""
  666.         for prefix, namespace in self.namespace_manager.namespaces():
  667.             yield prefix, namespace
  668.  
  669.     def absolutize(self, uri, defrag=1):
  670.         """Turn uri into an absolute URI if it's not one already"""
  671.         return self.namespace_manager.absolutize(uri, defrag)
  672.  
  673.     def serialize(self, destination=None, format="xml", base=None, encoding=None, **args):
  674.         """Serialize the Graph to destination
  675.  
  676.         If destination is None serialize method returns the serialization as a
  677.         string. Format defaults to xml (AKA rdf/xml).
  678.         """
  679.         serializer = plugin.get(format, Serializer)(self)
  680.         return serializer.serialize(destination, base=base, encoding=encoding, **args)
  681.  
  682.     def prepare_input_source(self, source, publicID=None):
  683.         if isinstance(source, InputSource):
  684.             input_source = source
  685.         else:
  686.             if hasattr(source, "read") and not isinstance(source, Namespace):
  687.                 # we need to make sure it's not an instance of Namespace since
  688.                 # Namespace instances have a read attr
  689.                 input_source = prepare_input_source(source)
  690.             else:
  691.                 location = self.absolutize(source)
  692.                 input_source = URLInputSource(location)
  693.                 publicID = publicID or location
  694.         if publicID:
  695.             input_source.setPublicId(publicID)
  696.         id = input_source.getPublicId()
  697.         if id is None:
  698.             #_logger.warning("no publicID set for source. Using '' for publicID.")
  699.             input_source.setPublicId("")
  700.         return input_source
  701.  
  702.     def parse(self, source, publicID=None, format="xml", **args):
  703.         """ Parse source into Graph
  704.  
  705.         If Graph is context-aware it'll get loaded into it's own context
  706.         (sub graph). Format defaults to xml (AKA rdf/xml). The publicID
  707.         argument is for specifying the logical URI for the case that it's
  708.         different from the physical source URI. Returns the context into which
  709.         the source was parsed.
  710.         """
  711.         source = self.prepare_input_source(source, publicID)
  712.         parser = plugin.get(format, Parser)()
  713.         parser.parse(source, self, **args)
  714.         return self
  715.  
  716.     def load(self, source, publicID=None, format="xml"):
  717.         self.parse(source, publicID, format)
  718.  
  719.     def query(self, strOrQuery, initBindings={}, initNs={}, DEBUG=False,
  720.               dataSetBase=None,
  721.               processor="sparql",
  722.               extensionFunctions={sparql.DESCRIBE:describe}):
  723.         """
  724.         Executes a SPARQL query (eventually will support Versa queries with same method) against this Graph
  725.         strOrQuery - Is either a string consisting of the SPARQL query or an instance of rdflib.sparql.bison.Query.Query
  726.         initBindings - A mapping from a Variable to an RDFLib term (used as initial bindings for SPARQL query)
  727.         initNS - A mapping from a namespace prefix to an instance of rdflib.Namespace (used for SPARQL query)
  728.         DEBUG - A boolean flag passed on to the SPARQL parser and evaluation engine
  729.         processor - The kind of RDF query (must be 'sparql' until Versa is ported)
  730.         """
  731.         assert processor == 'sparql',"SPARQL is currently the only supported RDF query language"
  732.         p = plugin.get(processor, sparql.Processor)(self)
  733.         return plugin.get('SPARQLQueryResult',QueryResult)(p.query(strOrQuery,
  734.                                                                    initBindings,
  735.                                                                    initNs, 
  736.                                                                    DEBUG, 
  737.                                                                    dataSetBase,
  738.                                                                    extensionFunctions))
  739.  
  740.         processor_plugin = plugin.get(processor, sparql.Processor)(self.store)
  741.         qresult_plugin = plugin.get('SPARQLQueryResult', QueryResult)
  742.  
  743.         res = processor_plugin.query(strOrQuery, 
  744.                                      initBindings, 
  745.                                      initNs, 
  746.                                      DEBUG, 
  747.                                      extensionFunctions=extensionFunctions)
  748.         return qresult_plugin(res)
  749.  
  750.     def n3(self):
  751.         """return an n3 identifier for the Graph"""
  752.         return "[%s]" % self.identifier.n3()
  753.  
  754.     def __reduce__(self):
  755.         return (Graph, (self.store, self.identifier,))
  756.  
  757.     def isomorphic(self, other):
  758.         # TODO: this is only an approximation.
  759.         if len(self) != len(other):
  760.             return False
  761.         for s, p, o in self:
  762.             if not isinstance(s, BNode) and not isinstance(o, BNode):
  763.                 if not (s, p, o) in other:
  764.                     return False
  765.         for s, p, o in other:
  766.             if not isinstance(s, BNode) and not isinstance(o, BNode):
  767.                 if not (s, p, o) in self:
  768.                     return False
  769.         # TODO: very well could be a false positive at this point yet.
  770.         return True
  771.  
  772.     def connected(self):
  773.         """Check if the Graph is connected
  774.  
  775.         The Graph is considered undirectional.
  776.  
  777.         Performs a search on the Graph, starting from a random node. Then
  778.         iteratively goes depth-first through the triplets where the node is
  779.         subject and object. Return True if all nodes have been visited and
  780.         False if it cannot continue and there are still unvisited nodes left.
  781.         """
  782.         all_nodes = list(self.all_nodes())
  783.         discovered = []
  784.  
  785.         # take a random one, could also always take the first one, doesn't
  786.         # really matter.
  787.         visiting = [all_nodes[random.randrange(len(all_nodes))]]
  788.         while visiting:
  789.             x = visiting.pop()
  790.             if x not in discovered:
  791.                 discovered.append(x)
  792.             for new_x in self.objects(subject=x):
  793.                 if new_x not in discovered and new_x not in visiting:
  794.                     visiting.append(new_x)
  795.             for new_x in self.subjects(object=x):
  796.                 if new_x not in discovered and new_x not in visiting:
  797.                     visiting.append(new_x)
  798.  
  799.         # optimisation by only considering length, since no new objects can
  800.         # be introduced anywhere.
  801.         if len(all_nodes) == len(discovered):
  802.             return True
  803.         else:
  804.             return False
  805.  
  806.     def all_nodes(self):
  807.         obj = set(self.objects())
  808.         allNodes = obj.union(set(self.subjects()))
  809.         return allNodes
  810.  
  811. class ConjunctiveGraph(Graph):
  812.  
  813.     def __init__(self, store='default', identifier=None):
  814.         super(ConjunctiveGraph, self).__init__(store)
  815.         assert self.store.context_aware, ("ConjunctiveGraph must be backed by"
  816.                                           " a context aware store.")
  817.         self.context_aware = True
  818.         self.default_context = Graph(store=self.store,
  819.                                      identifier=identifier or BNode())
  820.  
  821.     def __str__(self):
  822.         pattern = ("[a rdflib:ConjunctiveGraph;rdflib:storage "
  823.                    "[a rdflib:Store;rdfs:label '%s']]")
  824.         return pattern % self.store.__class__.__name__
  825.  
  826.     def add(self, (s, p, o)):
  827.         """Add the triple to the default context"""
  828.         self.store.add((s, p, o), context=self.default_context, quoted=False)
  829.  
  830.     def addN(self, quads):
  831.         """Add a sequence of triple with context"""
  832.         self.store.addN(quads)
  833.  
  834.     def remove(self, (s, p, o)):
  835.         """Removes from all its contexts"""
  836.         self.store.remove((s, p, o), context=None)
  837.  
  838.     def triples(self, (s, p, o)):
  839.         """Iterate over all the triples in the entire conjunctive graph"""
  840.         for (s, p, o), cg in self.store.triples((s, p, o), context=None):
  841.             yield s, p, o
  842.  
  843.     def quads(self,(s,p,o)):
  844.         """Iterate over all the quads in the entire conjunctive graph"""
  845.         for (s, p, o), cg in self.store.triples((s, p, o), context=None):
  846.             for ctx in cg:
  847.                 yield s, p, o, ctx
  848.             
  849.     def triples_choices(self, (s, p, o)):
  850.         """Iterate over all the triples in the entire conjunctive graph"""
  851.         for (s1, p1, o1), cg in self.store.triples_choices((s, p, o),
  852.                                                            context=None):
  853.             yield (s1, p1, o1)
  854.  
  855.     def __len__(self):
  856.         """Number of triples in the entire conjunctive graph"""
  857.         return self.store.__len__()
  858.  
  859.     def contexts(self, triple=None):
  860.         """Iterate over all contexts in the graph
  861.  
  862.         If triple is specified, iterate over all contexts the triple is in.
  863.         """
  864.         for context in self.store.contexts(triple):
  865.             yield context
  866.  
  867.     def remove_context(self, context):
  868.         """Removes the given context from the graph"""
  869.         self.store.remove((None, None, None), context)
  870.  
  871.     def context_id(self, uri, context_id=None):
  872.         """URI#context"""
  873.         uri = uri.split("#", 1)[0]
  874.         if context_id is None:
  875.             context_id = "#context"
  876.         return URIRef(context_id, base=uri)
  877.  
  878.     def parse(self, source, publicID=None, format="xml", **args):
  879.         """Parse source into Graph into it's own context (sub graph)
  880.  
  881.         Format defaults to xml (AKA rdf/xml). The publicID argument is for
  882.         specifying the logical URI for the case that it's different from the
  883.         physical source URI. Returns the context into which the source was
  884.         parsed. In the case of n3 it returns the root context.
  885.         """
  886.         source = self.prepare_input_source(source, publicID)
  887.         id = self.context_id(self.absolutize(source.getPublicId()))
  888.         context = Graph(store=self.store, identifier=id)
  889.         context.remove((None, None, None))
  890.         context.parse(source, publicID=publicID, format=format, **args)
  891.         return context
  892.  
  893.     def __reduce__(self):
  894.         return (ConjunctiveGraph, (self.store, self.identifier))
  895.  
  896.  
  897. class QuotedGraph(Graph):
  898.  
  899.     def __init__(self, store, identifier):
  900.         super(QuotedGraph, self).__init__(store, identifier)
  901.  
  902.     def add(self, triple):
  903.         """Add a triple with self as context"""
  904.         self.store.add(triple, self, quoted=True)
  905.  
  906.     def addN(self,quads):
  907.         """Add a sequence of triple with context"""
  908.         self.store.addN([(s,p,o,c) for s,p,o,c in quads
  909.                                    if isinstance(c, QuotedGraph)
  910.                                    and c.identifier is self.identifier])
  911.  
  912.     def n3(self):
  913.         """Return an n3 identifier for the Graph"""
  914.         return "{%s}" % self.identifier.n3()
  915.  
  916.     def __str__(self):
  917.         identifier = self.identifier.n3()
  918.         label = self.store.__class__.__name__
  919.         pattern = ("{this rdflib.identifier %s;rdflib:storage "
  920.                    "[a rdflib:Store;rdfs:label '%s']}")
  921.         return pattern % (identifier, label)
  922.  
  923.     def __reduce__(self):
  924.         return (QuotedGraph, (self.store, self.identifier))
  925.  
  926.  
  927. class GraphValue(QuotedGraph):
  928.     def __init__(self, store, identifier=None, graph=None):
  929.         if graph is not None:
  930.             assert identifier is None
  931.             np = store.node_pickler
  932.             identifier = md5()
  933.             s = list(graph.triples((None, None, None)))
  934.             s.sort()
  935.             for t in s:
  936.                 identifier.update("^".join((np.dumps(i) for i in t)))
  937.             identifier = URIRef("data:%s" % identifier.hexdigest())
  938.             super(GraphValue, self).__init__(store, identifier)
  939.             for t in graph:
  940.                 store.add(t, context=self)
  941.         else:
  942.             super(GraphValue, self).__init__(store, identifier)
  943.  
  944.  
  945.     def add(self, triple):
  946.         raise Exception("not mutable")
  947.  
  948.     def remove(self, triple):
  949.         raise Exception("not mutable")
  950.  
  951.     def __reduce__(self):
  952.         return (GraphValue, (self.store, self.identifier,))
  953.  
  954.  
  955. class Seq(object):
  956.     """Wrapper around an RDF Seq resource
  957.  
  958.     It implements a container type in Python with the order of the items
  959.     returned corresponding to the Seq content. It is based on the natural
  960.     ordering of the predicate names _1, _2, _3, etc, which is the
  961.     'implementation' of a sequence in RDF terms.
  962.     """
  963.  
  964.     def __init__(self, graph, subject):
  965.         """Parameters:
  966.  
  967.         - graph:
  968.             the graph containing the Seq
  969.  
  970.         - subject:
  971.             the subject of a Seq. Note that the init does not
  972.             check whether this is a Seq, this is done in whoever
  973.             creates this instance!
  974.         """
  975.  
  976.         _list = self._list = list()
  977.         LI_INDEX = RDF.RDFNS["_"]
  978.         for (p, o) in graph.predicate_objects(subject):
  979.             if p.startswith(LI_INDEX): #!= RDF.Seq: #
  980.                 i = int(p.replace(LI_INDEX, ''))
  981.                 _list.append((i, o))
  982.  
  983.         # here is the trick: the predicates are _1, _2, _3, etc. Ie,
  984.         # by sorting the keys (by integer) we have what we want!
  985.         _list.sort()
  986.  
  987.     def __iter__(self):
  988.         """Generator over the items in the Seq"""
  989.         for _, item in self._list:
  990.             yield item
  991.  
  992.     def __len__(self):
  993.         """Length of the Seq"""
  994.         return len(self._list)
  995.  
  996.     def __getitem__(self, index):
  997.         """Item given by index from the Seq"""
  998.         index, item = self._list.__getitem__(index)
  999.         return item
  1000.  
  1001.  
  1002. class BackwardCompatGraph(ConjunctiveGraph):
  1003.  
  1004.     def __init__(self, backend='default'):
  1005.         warnings.warn("Use ConjunctiveGraph instead. "
  1006.                       "( from rdflib.Graph import ConjunctiveGraph )",
  1007.                       DeprecationWarning, stacklevel=2)
  1008.         super(BackwardCompatGraph, self).__init__(store=backend)
  1009.  
  1010.     def __get_backend(self):
  1011.         return self.store
  1012.     backend = property(__get_backend)
  1013.  
  1014.     def open(self, configuration, create=True):
  1015.         return ConjunctiveGraph.open(self, configuration, create)
  1016.  
  1017.     def add(self, (s, p, o), context=None):
  1018.         """Add to to the given context or to the default context"""
  1019.         if context is not None:
  1020.             c = self.get_context(context)
  1021.             assert c.identifier == context, "%s != %s" % (c.identifier, context)
  1022.         else:
  1023.             c = self.default_context
  1024.         self.store.add((s, p, o), context=c, quoted=False)
  1025.  
  1026.     def remove(self, (s, p, o), context=None):
  1027.         """Remove from the given context or from the default context"""
  1028.         if context is not None:
  1029.             context = self.get_context(context)
  1030.         self.store.remove((s, p, o), context)
  1031.  
  1032.     def triples(self, (s, p, o), context=None):
  1033.         """Iterate over all the triples in the entire graph"""
  1034.         if context is not None:
  1035.             c = self.get_context(context)
  1036.             assert c.identifier == context
  1037.         else:
  1038.             c = None
  1039.         for (s, p, o), cg in self.store.triples((s, p, o), c):
  1040.             yield (s, p, o)
  1041.  
  1042.     def __len__(self, context=None):
  1043.         """Number of triples in the entire graph"""
  1044.         if context is not None:
  1045.             context = self.get_context(context)
  1046.         return self.store.__len__(context)
  1047.  
  1048.     def get_context(self, identifier, quoted=False):
  1049.         """Return a context graph for the given identifier
  1050.  
  1051.         identifier must be a URIRef or BNode.
  1052.         """
  1053.         assert isinstance(identifier, URIRef) or \
  1054.                isinstance(identifier, BNode), type(identifier)
  1055.         if quoted:
  1056.             assert False
  1057.             return QuotedGraph(self.store, identifier)
  1058.             #return QuotedGraph(self.store, Graph(store=self.store,
  1059.             #                                     identifier=identifier))
  1060.         else:
  1061.             return Graph(store=self.store, identifier=identifier,
  1062.                          namespace_manager=self)
  1063.             #return Graph(self.store, Graph(store=self.store,
  1064.             #                               identifier=identifier))
  1065.  
  1066.     def remove_context(self, context):
  1067.         """Remove the given context from the graph"""
  1068.         self.store.remove((None, None, None), self.get_context(context))
  1069.  
  1070.     def contexts(self, triple=None):
  1071.         """Iterate over all contexts in the graph
  1072.  
  1073.         If triple is specified, iterate over all contexts the triple is in.
  1074.         """
  1075.         for context in self.store.contexts(triple):
  1076.             yield context.identifier
  1077.  
  1078.     def subjects(self, predicate=None, object=None, context=None):
  1079.         """Generate subjects with the given predicate and object"""
  1080.         for s, p, o in self.triples((None, predicate, object), context):
  1081.             yield s
  1082.  
  1083.     def predicates(self, subject=None, object=None, context=None):
  1084.         """Generate predicates with the given subject and object"""
  1085.         for s, p, o in self.triples((subject, None, object), context):
  1086.             yield p
  1087.  
  1088.     def objects(self, subject=None, predicate=None, context=None):
  1089.         """Generate objects with the given subject and predicate"""
  1090.         for s, p, o in self.triples((subject, predicate, None), context):
  1091.             yield o
  1092.  
  1093.     def subject_predicates(self, object=None, context=None):
  1094.         """Generate (subject, predicate) tuples for the given object"""
  1095.         for s, p, o in self.triples((None, None, object), context):
  1096.             yield s, p
  1097.  
  1098.     def subject_objects(self, predicate=None, context=None):
  1099.         """Generate (subject, object) tuples for the given predicate"""
  1100.         for s, p, o in self.triples((None, predicate, None), context):
  1101.             yield s, o
  1102.  
  1103.     def predicate_objects(self, subject=None, context=None):
  1104.         """Generate (predicate, object) tuples for the given subject"""
  1105.         for s, p, o in self.triples((subject, None, None), context):
  1106.             yield p, o
  1107.  
  1108.     def __reduce__(self):
  1109.         return (BackwardCompatGraph, (self.store, self.identifier))
  1110.  
  1111.     def save(self, destination, format="xml", base=None, encoding=None):
  1112.         warnings.warn("Use serialize method instead. ",
  1113.                       DeprecationWarning, stacklevel=2)
  1114.         self.serialize(destination=destination, format=format, base=base,
  1115.                        encoding=encoding)
  1116.  
  1117. class ModificationException(Exception):
  1118.  
  1119.     def __init__(self):
  1120.         pass
  1121.  
  1122.     def __str__(self):
  1123.         return ("Modifications and transactional operations not allowed on "
  1124.                 "ReadOnlyGraphAggregate instances")
  1125.  
  1126. class UnSupportedAggregateOperation(Exception):
  1127.  
  1128.     def __init__(self):
  1129.         pass
  1130.  
  1131.     def __str__(self):
  1132.         return ("This operation is not supported by ReadOnlyGraphAggregate "
  1133.                 "instances")
  1134.  
  1135. class ReadOnlyGraphAggregate(ConjunctiveGraph):
  1136.     """Utility class for treating a set of graphs as a single graph
  1137.  
  1138.     Only read operations are supported (hence the name). Essentially a
  1139.     ConjunctiveGraph over an explicit subset of the entire store.
  1140.     """
  1141.  
  1142.     def __init__(self, graphs,store='default'):
  1143.         if store is not None:
  1144.             super(ReadOnlyGraphAggregate, self).__init__(store)
  1145.         assert isinstance(graphs, list) and graphs\
  1146.                and [g for g in graphs if isinstance(g, Graph)],\
  1147.                "graphs argument must be a list of Graphs!!"
  1148.         self.graphs = graphs
  1149.  
  1150.     def __repr__(self):
  1151.         return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)
  1152.  
  1153.     def destroy(self, configuration):
  1154.         raise ModificationException()
  1155.  
  1156.     #Transactional interfaces (optional)
  1157.     def commit(self):
  1158.         raise ModificationException()
  1159.  
  1160.     def rollback(self):
  1161.         raise ModificationException()
  1162.  
  1163.     def open(self, configuration, create=False):
  1164.         # TODO: is there a use case for this method?
  1165.         for graph in self.graphs:
  1166.             graph.open(self, configuration, create)
  1167.  
  1168.     def close(self):
  1169.         for graph in self.graphs:
  1170.             graph.close()
  1171.  
  1172.     def add(self, (s, p, o)):
  1173.         raise ModificationException()
  1174.  
  1175.     def addN(self, quads):
  1176.         raise ModificationException()
  1177.  
  1178.     def remove(self, (s, p, o)):
  1179.         raise ModificationException()
  1180.  
  1181.     def triples(self, (s, p, o)):
  1182.         for graph in self.graphs:
  1183.             for s1, p1, o1 in graph.triples((s, p, o)):
  1184.                 yield (s1, p1, o1)
  1185.  
  1186.     def quads(self,(s,p,o)):
  1187.         """Iterate over all the quads in the entire aggregate graph"""
  1188.         for graph in self.graphs:
  1189.             for s1, p1, o1 in graph.triples((s, p, o)):
  1190.                 yield (s1, p1, o1, graph)
  1191.  
  1192.     def __len__(self):
  1193.         return reduce(lambda x, y: x + y, [len(g) for g in self.graphs])
  1194.  
  1195.     def __hash__(self):
  1196.         raise UnSupportedAggregateOperation()
  1197.  
  1198.     def __cmp__(self, other):
  1199.         if other is None:
  1200.             return -1
  1201.         elif isinstance(other, Graph):
  1202.             return -1
  1203.         elif isinstance(other, ReadOnlyGraphAggregate):
  1204.             return cmp(self.graphs, other.graphs)
  1205.         else:
  1206.             return -1
  1207.  
  1208.     def __iadd__(self, other):
  1209.         raise ModificationException()
  1210.  
  1211.     def __isub__(self, other):
  1212.         raise ModificationException()
  1213.  
  1214.     # Conv. methods
  1215.  
  1216.     def triples_choices(self, (subject, predicate, object_), context=None):
  1217.         for graph in self.graphs:
  1218.             choices = graph.triples_choices((subject, predicate, object_))
  1219.             for (s, p, o) in choices:
  1220.                 yield (s, p, o)
  1221.  
  1222.     def qname(self, uri):
  1223.         raise UnSupportedAggregateOperation()
  1224.  
  1225.     def compute_qname(self, uri):
  1226.         raise UnSupportedAggregateOperation()
  1227.  
  1228.     def bind(self, prefix, namespace, override=True):
  1229.         raise UnSupportedAggregateOperation()
  1230.  
  1231.     def namespaces(self):
  1232.         if hasattr(self,'namespace_manager'):
  1233.             for prefix, namespace in self.namespace_manager.namespaces():
  1234.                 yield prefix, namespace
  1235.         else:
  1236.             for graph in self.graphs:
  1237.                 for prefix, namespace in graph.namespaces():
  1238.                     yield prefix, namespace
  1239.  
  1240.     def absolutize(self, uri, defrag=1):
  1241.         raise UnSupportedAggregateOperation()
  1242.  
  1243.     def parse(self, source, publicID=None, format="xml", **args):
  1244.         raise ModificationException()
  1245.  
  1246.     def n3(self):
  1247.         raise UnSupportedAggregateOperation()
  1248.  
  1249.     def __reduce__(self):
  1250.         raise UnSupportedAggregateOperation()
  1251.  
  1252.  
  1253. def test():
  1254.     import doctest
  1255.     doctest.testmod()
  1256.  
  1257. if __name__ == '__main__':
  1258.     test()
  1259.